<template>
  <!-- <a-card title="轨迹展示及轨迹回放" :bordered="false"> -->
  <a-alert style="margin-bottom: 10px;" message="一辆车一天最多一块钱，非必要请不要随便乱查！同一辆车一天内可以随便查" type="warning" />
  <a-form ref="mapperFormRef" :model="mapperWhere" :rules="mapperRules" :label-col="{ md: { span: 7 }, sm: { span: 24 } }"
    :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
    <a-row>
      <a-col>
        <a-form-item label="开始时间" name="date1">
          <a-date-picker v-model:value="mapperWhere.date1" valueFormat="YYYY-MM-DD HH:mm:ss"
            :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" placeholder="请输入装箱日期(客户要求的装箱时间)"
            class="ele-fluid" allow-clear />
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item label="结束时间" name="date2">
          <a-date-picker v-model:value="mapperWhere.date2" valueFormat="YYYY-MM-DD HH:mm:ss"
            :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" placeholder="请输入装箱日期(客户要求的装箱时间)"
            class="ele-fluid" allow-clear />
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item label="车牌" name="carNo">
          <!-- <a-input allow-clear :maxlength="200" placeholder="请输入车牌" v-model:value="carNo_s" autocomplete="off"
            disabled="disabled" /> -->
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item :wrapper-col="{ span: 24 }">
          <em></em>
          <a-space>
            <a-button type="primary" @click="goodsTransferTrack2">查询</a-button>
          </a-space>
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>

  <a-row style="margin: 0 0 10px 0;">
    <a-col :span="24">
      <a-space>
        <a-button type="primary" class="ele-btn-icon" @click="startTrackAnim">
          开始移动{{ props.aa }}
        </a-button>
        <a-button type="primary" class="ele-btn-icon" @click="pauseTrackAnim">
          暂停移动
        </a-button>
        <a-button type="primary" class="ele-btn-icon" @click="resumeTrackAnim">
          继续移动
        </a-button>
      </a-space>
    </a-col>
  </a-row>

  <!-- <a-row style="margin: 0 0 10px 0;">
      <a-col :span="24">
        <a-space>
         
    <button @click="goodsTransferTrack2">goodsTransferTrack</button> 
        </a-space>
      </a-col>
    </a-row> -->

  <div ref="trackMapRef" style="height: 60vh; width: 100%; margin-bottom: 16px"></div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, reactive } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useThemeStore } from '@/store/modules/theme';
import { message } from 'ant-design-vue';
import useFormData from '@/utils/use-form-data';
import { storeToRefs } from 'pinia';
import { MAP_KEY, API_BASE_URL } from '@/config/setting';
import dayjs from 'dayjs';

import { goodsTransferTrack, carMapper } from '@/api/order/mapper';


const props = defineProps({
  carNo_s: String,
  date1_s: String,
  date2_s: String,
})

let mapperFormRef = ref(null)
let mapperWhere = reactive({
  date1: dayjs().subtract(1, 'day'),
  date2: dayjs(),
  carNo: '浙B5G713',
})




const { form: mapperForm, resetFields: mapperFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
});
// 表单验证规则
const mapperRules = reactive({
  date1: [
    {
      required: true,
      type: 'string',
      validator: async (_rule, value) => {
        if (!value) {
          return Promise.reject('开始时间');
        }
        return Promise.resolve();
      },
      trigger: 'blur'
    }
  ],
  date2: [
    {
      required: true,
      type: 'string',
      validator: async (_rule, value) => {
        if (!value) {
          return Promise.reject('结束时间');
        }
        // console.log(dayjs(mapperWhere.date1)< dayjs(mapperWhere.date2), dayjs(mapperWhere.date1).add(1, 'day')> dayjs(mapperWhere.date2))
        if (!(dayjs(mapperWhere.date1) <= dayjs(mapperWhere.date2) && dayjs(mapperWhere.date1).add(1, 'day') >= dayjs(mapperWhere.date2))) {
          return Promise.reject('开始时间和结束时间不能超过1天');
        }
        return Promise.resolve();
      },
      trigger: 'blur'
    }
  ],
  carNo: [
    {
      required: true,
      message: '请输入车牌',
      type: 'string',
    }
  ],
  password2: [
    {
      required: true,
      type: 'string',
      validator: async (_rule, value) => {
        if (!value) {
          return Promise.reject('请再次输入新密码');
        }
        if (value !== form.password) {
          return Promise.reject('两次输入密码不一致');
        }
        return Promise.resolve();
      },
      trigger: 'blur'
    }
  ]
});

const themeStore = useThemeStore();
const { darkMode } = storeToRefs(themeStore);

//
const trackMapRef = ref(null);

// 小车轨迹地图的实例
let mapInsTrack;

// 小车的 marker
let carMarker;

// 轨迹路线
let lineData = [
  [116.478935, 39.997761],
  [116.478939, 39.997825],
  [116.478912, 39.998549],
  [116.478912, 39.998549],
  [116.478998, 39.998555],
  [116.478998, 39.998555],
  [116.479282, 39.99856],
  [116.479658, 39.998528],
  [116.480151, 39.998453],
  [116.480784, 39.998302],
  [116.480784, 39.998302],
  [116.481149, 39.998184],
  [116.481573, 39.997997],
  [116.481863, 39.997846],
  [116.482072, 39.997718],
  [116.482362, 39.997718],
  [116.483633, 39.998935],
  [116.48367, 39.998968],
  [116.484648, 39.999861]
];

/* 渲染轨迹回放地图 */
const renderTrackMap = () => {
  AMapLoader.load({
    key: MAP_KEY,
    version: '2.0',
    plugins: ['AMap.MoveAnimation', 'AMap.Marker', 'AMap.Polyline']
  })
    .then((AMap) => {
      // 渲染地图
      const option = {
        zoom: 8, // 初缩放级别
        center: [121.633815, 29.840605], // 初始中心点
        mapStyle: darkMode.value ? 'amap://styles/dark' : void 0
      };
      mapInsTrack = new AMap.Map(trackMapRef.value, option);

    })
    .catch((e) => {
      console.error(e);
    });
};

/* 开始轨迹回放动画 */
const startTrackAnim = () => {
  if (carMarker) {
    carMarker.stopMove();
    //https://www.5axxw.com/questions/simple/bdwt06
    carMarker.moveAlong(lineData, 240, {
      duration: 200,
      autoRotation: true,
    });
  }
};

/* 暂停轨迹回放动画 */
const pauseTrackAnim = () => {
  if (carMarker) {
    carMarker.pauseMove();
  }
};

/* 继续开始轨迹回放动画 */
const resumeTrackAnim = () => {
  if (carMarker) {
    carMarker.resumeMove();
  }
};

/* 渲染地图 */
onMounted(() => {
  renderTrackMap();
});

/* 销毁地图 */
onUnmounted(() => {
  if (mapInsTrack) {
    mapInsTrack.destroy();
  }
});

/* 同步框架暗黑模式切换 */
watch(darkMode, () => {
  if (mapInsTrack) {
    if (darkMode.value) {
      mapInsTrack.setMapStyle('amap://styles/dark');
    } else {
      mapInsTrack.setMapStyle('amap://styles/normal');
    }
  }
});

let passedPolyline = null
let passedPolyline2 = null
const goodsTransferTrack2 = () => {
  mapperFormRef.value.validate().then(() => {
    goodsTransferTrack({ 'vclN': mapperWhere.carNo, 'qryBtm': mapperWhere.date1, 'qryEtm': mapperWhere.date2 }).then((msg) => {
      // goodsTransferTrack({ 'vclN': '陕YH0009', 'qryBtm': '2023-05-19 01:01:01', 'qryEtm': '2023-05-19 20:01:01' }).then((msg) => {
      if (carMarker) {
        carMarker.stopMove();
        mapInsTrack.remove(carMarker);
      }
      if (passedPolyline) {
        mapInsTrack.remove(passedPolyline);
      }
      if (passedPolyline2) {
        mapInsTrack.remove(passedPolyline2);
      }
      lineData = msg
      // 创建小车 marker
      carMarker = new AMap.Marker({
        map: mapInsTrack,
        position: msg[0],
        // icon: 'https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png',
        // offset: new AMap.Pixel(-13, -26)
        icon: API_BASE_URL + '/file/20230517/a.png?path2=chf_setting',
        offset: new AMap.Pixel(-26, -13),
        // angle: -60,
      });
      carMarker.setLabel({
        direction: 'right',
        offset: new AMap.Pixel(10, 0),  //设置文本标注偏移量
        content: "<div class='info'>我是 marker 的 label 标签</div>", //设置文本标注内容
      });
      // 绘制轨迹
      passedPolyline2 = new AMap.Polyline({
        map: mapInsTrack,
        path: lineData,
        showDir: true,
        strokeColor: '#2288FF', // 线颜色
        strokeOpacity: 1, // 线透明度
        strokeWeight: 6 // 线宽
        //strokeStyle: 'solid'  // 线样式
      });
      // 通过的轨迹
      passedPolyline = new AMap.Polyline({
        map: mapInsTrack,
        showDir: true,
        strokeColor: '#44BB55', // 线颜色
        strokeOpacity: 1, // 线透明度
        strokeWeight: 6 // 线宽
      });
      // 小车移动回调
      carMarker.on('moving', (e) => {
        passedPolyline.setPath(e.passedPath);
      });
      // 地图自适应
      mapInsTrack.setFitView();
    }).catch((e) => {
      message.error('无轨迹');
    });
  })

}
</script>
